package services;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import pojo.FileSharePOJO;
import pojo.LogUtil;
import pojo.PairValue;

import sun.misc.IOUtils;
import util.ClientSender;
import util.Common;
import util.XMLBuidler;

import DataAccess.FileShareDA;
import DataAccess.LogThaoTacDA;

import com.mysql.jdbc.BufferRow;
//import com.sun.security.ntlm.Client;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/FileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUploadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final PrintWriter out = response.getWriter();
		String path = "";
		try {
			String nguoiDung = request.getParameter(Protocol.NGUOI_DUNG).trim();
			final String idNhom = request.getParameter(Protocol.ID_NHOM).trim();
			String ghiChu=request.getParameter(Protocol.GHI_CHU);
			String realPath = request.getRealPath("/");
			Part pFile = request.getPart("file");
			InputStream is = request.getPart(pFile.getName()).getInputStream();
			String fileName = getFileName(pFile);
			String extName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			path = nguoiDung + "_" + System.currentTimeMillis() + extName;
			File f = new File(realPath + "/" + Protocol.DIR + "/" + path);
			FileOutputStream os = new FileOutputStream(f);		
			byte[] b = new byte[1024];
			int i = 0;
			int len = is.available();
			int per = 0;
			int temp=0;
			int rLen;
			while ((rLen=is.read(b)) != -1) {
				
				per = (int) (1024 * (float) i / len * 100);
				
				if(per>temp){
					out.println(per);
					temp=per;
				}
				os.write(b,0,rLen);
				i++;
			}

			os.flush();
			os.close();		
			is.close();
			//Thêm để test
//			out.println(realPath + "/" + Protocol.DIR + "/" + path);
			//
			FileSharePOJO file = new FileSharePOJO();
			file.setIdNhom(Integer.parseInt(idNhom));
			file.setNguoiUp(nguoiDung);
			file.setPath(path);
			file.setTenFile(fileName);
			file.setGhiChu(ghiChu);
			file.setThoiGian(System.currentTimeMillis());
			new FileShareDA().insert(file);
			
			//Thêm để test
//			ArrayList<FileSharePOJO> arr=new ArrayList<FileSharePOJO>();
//			arr.add(file);
//			out.println(XMLBuidler.danhSachFile(arr));
			/////
			final ArrayList<FileSharePOJO> lstFile=new ArrayList<FileSharePOJO>();
			lstFile.add(file);
			
			//Ghi log
			new LogThaoTacDA().insert(nguoiDung,file.getId()+"",file.getIdNhom(),LogUtil.SHARE_FILE);
			Thread t=new Thread(new Runnable() {
				
				@Override
				public void run() {
					// Gửi thông tin tới các thành viên trong nhóm
					ArrayList<PairValue> params=new ArrayList<PairValue>();
					params.add(new PairValue(Protocol.CMD, Protocol.SHARE_FILE));
					params.add(new PairValue(Protocol.NOI_DUNG, XMLBuidler.danhSachFile(lstFile)));
					try {
					Thread.sleep(5000);
						ClientSender.sendToGroup(Integer.parseInt(idNhom), params);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace(out);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace(out);
					}
				}
			});
			t.run();
			
		} catch (SQLException e) {
			Common.delFile(path);
			e.printStackTrace(System.out);

			e.printStackTrace(out);

		} catch (Exception e) {
			e.printStackTrace(out);
			e.printStackTrace(System.out);
		}
		// Thêm để test
		// out.println("OK chang bi sao");
		//
		out.close();
	}

	private String getFileName(Part part) {
		// String partHeader = part.getHeader("content-disposition");
		// logger.info("Part Header = " + partHeader);
		for (String cd : part.getHeader("content-disposition").split(";")) {
			if (cd.trim().startsWith("filename")) {
				return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
			}
		}
		return null;

	}

	private String getContent(Part part) {
		String rs = "";

		try {
			InputStreamReader isr = new InputStreamReader(part.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			rs = br.readLine();
		} catch (IOException e) {
			rs = "";
		}

		return rs;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}
